class VastApi
  class Listings < Array
    attr_reader :response, :xml, :url, :vast, :attributes

    delegate :find, :find!,  :to=>:vast

    def initialize(vast)
      @vast = vast
      @url = "#{@vast.api_url}listings/-/#{@vast.category}?#{@vast.query}"
      @response = Typhoeus::Request.get(@url)
      @xml = Nokogiri::XML(@response.body)
      populate
    end

    def attr(var_name)
      if var = @xml.at(var_name)
        var.text
      elsif var = @xml.at('//v:'+var_name)
        var.text
      elsif var = @xml.at('//o:'+var_name)
        var.text
      else
        nil
      end
    end

    def query
      if @query.nil?
        @query = {}
        @xml.at('//o:Query').attributes.each do |name,value|
          @query[name] = value.value
        end
      end
      @query
    end

    def self.get(vast,url)
      response = Typhoeus::Request.get(url)
      Entry.new(vast, Nokogiri::XML(response.body).at('entry'))
    end

    def attributes
      @attributes ||= vast.attributes
    end

    private
    def populate
      @xml.css("entry").each do |entry|
        e = @vast.create_entry(entry)
        if e.kind_of? VastApi::Attributes::Entry
          @attributes ||= {}
          @attributes[entry.at_xpath('v:attribute')['id']] = e
        elsif e.kind_of? VastApi::Listings::Entry
          self << e
        end
      end
    end
  end
end

